//
//  CodableObject.swift
//  cabbage_serialization
//
//  Created by dfsx6 on 2021/9/6.
//

import UIKit



//MARK:-
class CodableObject: NSObject, Codable {

    enum ListItemMode: Int, Codable {
        case one    = 0
        case big    = 1
        case more   = 2
        case zero   = 3
    }

    public var id: Int?
    public var columnName: String?
    public var publishTime: Date?
    public var listItemMode: CodableObject.ListItemMode?

    enum CodingKeys: String, CodingKey {
        case id
        case columnName = "column_name"
        case publishTime = "publish_time"
        case listItemMode = "list_item_mode"
    }

    required init(from decoder: Decoder) throws {
        guard let container = try? decoder.container(keyedBy: CodingKeys.self) else {
            return
        }
        id = try? container.decode(Int.self, forKey: .id)
        columnName = try? container.decode(String.self, forKey: .columnName)
        publishTime = try? container.decode(Date.self, forKey: .publishTime)
        listItemMode = try? container.decode(ListItemMode.self, forKey: .listItemMode)
    }
}


//MARK:-
extension CodableObject {
    
    override var description: String {
        var des = ""
        des += "\n id = \(String(describing: id))"
        des += "\n columnName = \(String(describing: columnName))"
        des += "\n publishTime = \(String(describing: publishTime))"
        des += "\n listItemMode = \(String(describing: listItemMode))"

        return des
    }

    
    public static func serialization() {
        
        guard let url = Bundle.main.url(forResource: "content", withExtension: "json") else {
            print("read cms json error")
            return
        }
        
        do {
            let data = try Data.init(contentsOf: url)
            serialization(from: data)
            
        } catch let error {
            print(error.localizedDescription)
        }

    }
    
    
    public static func serialization(from data: Data) {
        
        do {
            let object = try JSONDecoder.init().decode(CodableObject.self, from: data)
            print(object)
            
        } catch let error {
            print(error.localizedDescription)
        }
    }
}
